package com.ls.pattern.proxy.dynamicproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author 挥之以墨
 */
public class CgLibDemo {

    public void sayHello(String name) {
        System.out.println("Hello my name is " + name);
    }

    public void sayBye() {
        System.out.println("bye bye");
    }

    static class Cglib implements MethodInterceptor {

        public <T> T getInstance(Class<T> superClass) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(superClass);
            enhancer.setCallback(this);
            return (T) enhancer.create();
        }

        @Override
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            System.out.println("proxy in");
            proxy.invokeSuper(obj, args);
            System.out.println("proxy out");
            return null;
        }
    }

    public static void main(String[] args) {
        CgLibDemo instance = new Cglib().getInstance(CgLibDemo.class);
        instance.sayHello("double");
        instance.sayBye();
    }

}
